package com.wuliu.driver.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Paths;

@Component
public class Erweima {
    @Autowired
    private UploadImg  uploadImg;
    @Autowired
    private FileConvertUtil fileConvertUtil;
    public String createQRCode(String data, String path) {
        // 输出文件路径
        String filePath = path+".png";
        // 二维码尺寸（像素）
        int width = 300;
        int height = 300;

        try {
            // 生成二维码并保存为PNG文件
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", Paths.get(filePath));
            System.out.println("二维码已生成到: " + filePath);
            File file = new File(filePath);
            MultipartFile convert = fileConvertUtil.convert(file);
            String upload = uploadImg.upload(convert);
            System.out.println(upload);
            if (upload!=null && !upload.equals("")){
                return upload;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
